package com.pybox.service;

import com.pybox.common.utils.JdbcTemplateUtils;
import com.pybox.common.utils.ParamUtils;
import com.pybox.dto.TCabinetsDto;
import com.pybox.entity.TVehicle;
import com.pybox.repository.VehicleRepository;
import com.pybox.util.CopyUtils;
import com.pybox.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author LeiYang
 * @title: TVehicleService
 * @projectName pybox
 * @description: TODO
 * @date 2019/7/2214:58
 */
@Service
@Transactional
public class TVehicleService {

    @Autowired
    private VehicleRepository vehicleRepository;

    @Autowired
    private JdbcTemplateUtils jdbcTemplateUtils;


    public Page<TVehicle> page(Integer pageNo, Integer pageSize, Map<String, String> paramMap) {

        Pageable pageable = new PageRequest(pageNo - 1, pageSize);
        List<Object> object = new ArrayList<>();
        //默认只能看自己一个公司的
        StringBuffer sql = new StringBuffer("SELECT\n" +
                "\ttm.Id,\n" +
                "\ttm.model,\n" +
                "\ttm.color,\n" +
                "\ttm.brand,\n" +
                "\ttm.branch,\n" +
                "\ttm.utime,\n" +
                "\ttm.ctime \n" +
                "FROM\n" +
                "\tt_models tm WHERE 1 = 1");
        StringBuffer where = new ParamUtils().getTVehicleParams(sql, paramMap);

        Page<TVehicle> data = jdbcTemplateUtils.page(where, object, TVehicle.class, pageNo, pageSize);

        Page<TVehicle> page = new PageImpl<>(data.getContent(), pageable, data.getTotalElements());

        return page;
    }


    public TVehicle detail(Integer id) {
        return vehicleRepository.findOne(id);
    }


    public boolean update(TVehicle source) {

        source.setCustomer_id(UserUtils.getCustomerId().toString());

        if (null == source.getId()) {  //新增
            source.setId(null);
            source.setCtime(new Date());
            vehicleRepository.save(source);
            return true;
        }
        //更新
        source.setUtime(new Date());
        vehicleRepository.save(source);
        return true;
    }

    public void remove(Integer id) {
        vehicleRepository.delete(id);
    }
}
